<template>
  <div class="personal-info-container">
    <div class="personal-info-header">
      <h2>个人信息设置</h2>
      <p class="personal-info-subtitle">管理您的个人资料和公开信息</p>
    </div>

    <a-card class="personal-info-card">
      <a-form
        :model="personalInfo"
        :rules="personalInfoRules"
        ref="personalInfoFormRef"
        layout="vertical"
        class="personal-info-form"
      >
        <div class="personal-info-avatar">
          <div class="avatar-uploader-wrapper">
            <a-avatar
              :src="personalInfo.avatar"
              :size="128"
              class="avatar-large"
            >
              <UserOutlined v-if="!personalInfo.avatar" />
            </a-avatar>
            <div class="avatar-uploader-overlay" @click="handleAvatarUpload">
              <CameraOutlined />
              <span>更换头像</span>
            </div>
            <input
              ref="avatarInput"
              type="file"
              accept="image/*"
              style="display: none"
              @change="handleAvatarChange"
            />
          </div>
          <div class="avatar-hint">
            <p>支持 JPG、PNG 格式，文件大小不超过 2MB</p>
          </div>
        </div>

        <div class="form-fields-container">
          <a-form-item name="name" label="姓名">
            <a-input
              v-model:value="personalInfo.name"
              placeholder="请输入姓名"
              class="form-input"
            />
          </a-form-item>

          <a-form-item name="title" label="职位/头衔">
            <a-input
              v-model:value="personalInfo.title"
              placeholder="请输入职位或头衔"
              class="form-input"
            />
          </a-form-item>

          <a-form-item name="email" label="电子邮箱">
            <a-input
              v-model:value="personalInfo.email"
              placeholder="请输入电子邮箱"
              type="email"
              class="form-input"
            />
          </a-form-item>

          <a-form-item name="website" label="个人网站">
            <a-input
              v-model:value="personalInfo.website"
              placeholder="请输入个人网站地址"
              class="form-input"
            />
          </a-form-item>

          <a-form-item name="description" label="个人简介">
            <a-textarea
              v-model:value="personalInfo.description"
              placeholder="请输入个人简介"
              :rows="4"
              class="form-textarea"
            />
          </a-form-item>

          <a-form-item label="联系方式" class="contact-methods-section">
            <div
              v-for="(contact, index) in personalInfo.contactMethods"
              :key="contact.id"
              class="contact-method-item"
            >
              <div class="contact-method-controls">
                <a-select
                  v-model:value="contact.type"
                  placeholder="选择联系方式类型"
                  class="contact-type-select"
                >
                  <a-select-option
                    v-for="type in contactTypes"
                    :key="type.value"
                    :value="type.value"
                  >
                    {{ type.label }}
                  </a-select-option>
                </a-select>
                <a-input
                  v-model:value="contact.value"
                  placeholder="请输入联系方式"
                  class="contact-value-input"
                >
                  <template #prefix>
                    <component :is="getContactIcon(contact.type)" /> </template
                ></a-input>
                <div class="visibility-toggle">
                  <span class="visibility-label">显示</span>
                  <a-switch
                    v-model:checked="contact.visible"
                    class="visibility-switch"
                  >
                    <template #checked-icon>
                      <CheckOutlined />
                    </template>
                    <template #un-checked-icon>
                      <CloseOutlined />
                    </template>
                  </a-switch>
                </div>
                <a-button
                  type="text"
                  danger
                  @click="removeContactMethod(contact.id)"
                  class="remove-contact-btn"
                >
                  删除
                </a-button>
              </div>
              <div
                v-if="index === personalInfo.contactMethods.length - 1"
                class="add-contact-btn-wrapper"
              >
                <a-button
                  type="dashed"
                  @click="addContactMethod"
                  class="add-contact-btn"
                >
                  <PlusOutlined />
                  添加联系方式
                </a-button>
              </div>
            </div>
          </a-form-item>

          <a-form-item name="about" label="关于我">
            <div class="editor-wrapper">
              <div class="editor-toolbar">
                <div class="toolbar-info">
                  <InfoCircleOutlined />
                  <span>支持拖拽上传图片，Ctrl+S 快速保存</span>
                </div>
              </div>
              <div class="markdown-editor-container enhanced-editor">
                <v-md-editor
                  :model-value="personalInfo.about || ''"
                  @update:model-value="(val) => (personalInfo.about = val)"
                  height="400px"
                  :disabled-menus="[]"
                  :include-level="[1, 2, 3, 4, 5, 6]"
                  @upload-image="handleAboutImageUpload"
                  @save="handleSave"
                  @change="handleAboutChange"
                  placeholder="开始编辑你的关于我介绍...&#10;&#10;支持Markdown语法：&#10;- **加粗文字**&#10;- *斜体文字*&#10;- # 标题&#10;- ```代码块```&#10;- [链接文字](链接地址)"
                />
              </div>
            </div>
          </a-form-item>
        </div>

        <div class="form-actions">
          <a-button
            type="primary"
            @click="handleSave"
            :loading="loading"
            class="save-button"
          >
            保存设置
          </a-button>
          <a-button
            style="margin-left: 16px"
            @click="handleCancel"
            class="cancel-button"
          >
            取消
          </a-button>
        </div>
      </a-form>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { message } from "ant-design-vue";
import { settingApi } from "@/api/setting";
import { eventBus } from "@/utils/eventBus";
import VMdEditor from "@kangc/v-md-editor";
import "@kangc/v-md-editor/lib/style/base-editor.css";
import githubTheme from "@kangc/v-md-editor/lib/theme/github.js";
import "@kangc/v-md-editor/lib/theme/style/github.css";

// 引入highlight.js
import hljs from "highlight.js";
import "highlight.js/styles/github.css";

// 配置主题
VMdEditor.use(githubTheme, {
  Hljs: hljs,
});

// 全局错误处理
window.addEventListener("error", (e) => {
  if (
    e.message.includes("ResizeObserver loop limit exceeded") ||
    e.message.includes(
      "ResizeObserver loop completed with undelivered notifications"
    )
  ) {
    e.stopImmediatePropagation();
    return false;
  }
});

const loading = ref(false);
const personalInfoFormRef = ref();
const avatarInput = ref();
const personalInfo = reactive({
  name: "",
  title: "",
  email: "",
  website: "",
  description:
    "热爱技术，专注于前端开发，善于解决复杂问题，喜欢分享和学习新知识。",
  about: "",
  aboutHtml: "", // 添加HTML版本
  avatar: "",
  avatarUrl: "",
  contactMethods: [
    {
      id: "1",
      type: "phone",
      value: "",
      visible: false,
    },
    {
      id: "2",
      type: "email",
      value: "",
      visible: false,
    },
  ],
});

const personalInfoRules = {
  name: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 1, max: 20, message: "姓名长度在 1 到 20 个字符", trigger: "blur" },
  ],
  title: [
    { required: true, message: "请输入职位或头衔", trigger: "blur" },
    {
      min: 1,
      max: 50,
      message: "职位或头衔长度在 1 到 50 个字符",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入电子邮箱", trigger: "blur" },
    { type: "email", message: "请输入有效的电子邮箱地址", trigger: "blur" },
  ],
  website: [
    {
      pattern: /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([\/\w .-]*)*\/?$/,
      message: "请输入有效的网址",
      trigger: "blur",
    },
  ],
  description: [
    { required: true, message: "请输入个人简介", trigger: "blur" },
    {
      min: 1,
      max: 200,
      message: "个人简介长度在 1 到 200 个字符",
      trigger: "blur",
    },
  ],
  about: [
    { required: true, message: "请输入关于我的详细介绍", trigger: "blur" },
    {
      min: 1,
      max: 2000,
      message: "关于我的详细介绍长度在 1 到 2000 个字符",
      trigger: "blur",
    },
  ],
};

// 联系方式类型配置
const contactTypes = [
  { value: "phone", label: "手机", icon: "PhoneOutlined" },
  { value: "email", label: "邮箱", icon: "MailOutlined" },
  { value: "github", label: "GitHub", icon: "GithubOutlined" },
  { value: "wechat", label: "微信", icon: "WechatOutlined" },
  { value: "Weibo", label: "微博", icon: "WeiboCircleOutlined" },
  { value: "zhihu", label: "知乎", icon: "ZhihuOutlined" },
  { value: "qq", label: "QQ", icon: "QqOutlined" },
];

// 添加新的联系方式
const addContactMethod = () => {
  personalInfo.contactMethods.push({
    id: Date.now().toString(),
    type: "phone",
    value: "",
    visible: false,
  });
};

// 删除联系方式
const removeContactMethod = (id) => {
  if (personalInfo.contactMethods.length <= 1) {
    message.warning("至少保留一个联系方式");
    return;
  }
  personalInfo.contactMethods = personalInfo.contactMethods.filter(
    (item) => item.id !== id
  );
};

// 获取联系方式对应的图标名称
const getContactIcon = (type) => {
  const typeMap = {
    phone: "PhoneOutlined",
    email: "MailOutlined",
    github: "GithubOutlined",
    gitee: "GithubOutlined",
    linkedin: "LinkedinOutlined",
    twitter: "TwitterOutlined",
    wechat: "WechatOutlined",
    Weibo: "WeiboCircleOutlined",
    zhihu: "ZhihuOutlined",
    qq: "QqOutlined",
  };
  return typeMap[type] || null;
};

const fetchPersonalInfo = async () => {
  try {
    loading.value = true;
    const response = await settingApi.getPersonalInfo();
    if (response.code === 200 && response.data && response.data.data) {
      const data = response.data.data;
      personalInfo.name = data.name || "";
      personalInfo.title = data.title || "";
      personalInfo.description = data.description || "";
      // Ensure about is always a string, never null or undefined
      personalInfo.about = String(data.about || "");
      personalInfo.aboutHtml = data.aboutHtml || "";
      personalInfo.avatarUrl = data.avatar || "";
      personalInfo.avatar =
        import.meta.env.VITE_API_BASE_URL + (data.avatar || "");

      // Convert contact array to contactMethods format
      if (data.contact && Array.isArray(data.contact)) {
        personalInfo.contactMethods = data.contact.map((contact, index) => ({
          id: (index + 1).toString(),
          type: contact.type || "email",
          value: contact.value || "",
          visible: contact.visible || false,
        }));
      }

      // Extract email from contact if available
      const emailContact = data.contact?.find((c) => c.type === "email");
      if (emailContact) {
        personalInfo.email = emailContact.value;
      }

      message.success("个人信息加载成功");
    }
  } catch (error) {
    message.error("获取个人信息失败");
  } finally {
    loading.value = false;
  }
};

const handleAvatarUpload = () => {
  avatarInput.value?.click();
};

const handleAvatarChange = async (e) => {
  const file = e.target.files[0];
  if (file) {
    // 检查文件大小
    if (file.size > 2 * 1024 * 1024) {
      message.error("文件大小不能超过2MB");
      return;
    }

    try {
      loading.value = true;
      const formData = new FormData();
      formData.append("file", file);

      const response = await settingApi.uploadAvatar(formData);
      if (response.code === 200 && response.data) {
        personalInfo.avatarUrl = response.data.url;
        personalInfo.avatar =
          import.meta.env.VITE_API_BASE_URL + response.data.url;

        message.success("头像上传成功");
        // 触发个人信息更新事件，更新顶部栏的头像
        eventBus.emit("personalInfoUpdated");
      } else {
        message.error(response.message || "头像上传失败");
      }
    } catch (error) {
      message.error("头像上传失败");
    } finally {
      loading.value = false;
      // 清空input，以便可以重复上传同一个文件
      e.target.value = "";
    }
  }
};

// 内容变化时同步更新HTML
const handleAboutChange = (text, html) => {
  personalInfo.aboutHtml = html;
};

// 富文本编辑器图片上传处理
const handleAboutImageUpload = (event, insertImage) => {
  const file = event.target.files[0];
  if (!file) return;

  // 检查文件类型
  if (!file.type.startsWith("image/")) {
    message.error("请选择图片文件");
    return;
  }

  // 检查文件大小 (最大5MB)
  if (file.size > 5 * 1024 * 1024) {
    message.error("图片大小不能超过5MB");
    return;
  }

  try {
    const reader = new FileReader();
    reader.onload = (e) => {
      insertImage({
        url: e.target.result,
        desc: file.name,
      });
    };
    reader.readAsDataURL(file);
  } catch (error) {
    message.error("图片处理失败");
  }
};

const handleSave = async () => {
  try {
    await personalInfoFormRef.value.validate();
    loading.value = true;

    const personalInfoData = {
      name: personalInfo.name,
      title: personalInfo.title,
      email: personalInfo.email,
      website: personalInfo.website,
      description: personalInfo.description,
      about: personalInfo.about,
      aboutHtml: personalInfo.aboutHtml,
      avatar: personalInfo.avatarUrl,
      contactMethods: personalInfo.contactMethods,
    };

    const response = await settingApi.updatePersonalInfo(personalInfoData);
    if (response.code === 200) {
      message.success("保存成功");
      // 触发个人信息更新事件，更新顶部栏的头像和名称
      eventBus.emit("personalInfoUpdated");
    } else {
      message.error(response.message || "保存失败，请重试");
    }
  } catch (error) {
    message.error(error.message || "保存失败，请重试");
  } finally {
    loading.value = false;
  }
};

const handleCancel = () => {
  fetchPersonalInfo();
  personalInfoFormRef.value?.resetFields();
};

onMounted(() => {
  fetchPersonalInfo();
});
</script>

<style scoped>
/* 个人信息容器 */
.personal-info-container {
  padding: 24px;
  min-height: 100vh;
}

/* 个人信息头部 */
.personal-info-header {
  margin-bottom: 32px;
  animation: fadeIn 0.5s ease-out;
}

.personal-info-header h2 {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.personal-info-subtitle {
  color: #666;
  font-size: 16px;
}

/* 个人信息卡片 */
.personal-info-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  animation: fadeIn 0.5s ease-out 0.1s both;
}

/* 个人信息表单 */
.personal-info-form {
  padding: 32px;
}

/* 头像上传区域 */
.personal-info-avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 32px;
}

.avatar-uploader-wrapper {
  position: relative;
  margin-bottom: 16px;
}

.avatar-large {
  width: 128px;
  height: 128px;
  border: 4px solid #f0f0f0;
  transition: all 0.3s ease;
}

.avatar-uploader-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  cursor: pointer;
  border-radius: 50%;
}

.avatar-uploader-wrapper:hover .avatar-uploader-overlay {
  opacity: 1;
}

.avatar-hint {
  text-align: center;
}

.avatar-hint p {
  color: #999;
  font-size: 14px;
  margin: 0;
}

/* 表单字段容器 */
.form-fields-container {
  max-width: 1000px;
  margin: 0 auto;
}

/* 表单输入框 */
.form-input {
  height: 40px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.form-input:focus {
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 表单文本域 */
.form-textarea {
  border-radius: 6px;
  transition: all 0.3s ease;
  resize: vertical;
  min-height: 100px;
}

.form-textarea:focus {
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 联系方式模块样式 */
.contact-methods-section {
  margin-bottom: 24px;
}

.contact-method-item {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f5f5f5;
  border-radius: 8px;
  transition: background-color 0.3s ease;
}

.contact-method-item:hover {
  background-color: #f0f0f0;
}

.contact-method-controls {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.contact-type-select {
  width: 160px;
}

.contact-value-input {
  flex: 1;
  min-width: 300px;
}

.visibility-toggle {
  display: flex;
  align-items: center;
  gap: 8px;
}

.visibility-label {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
}

.visibility-switch {
  display: inline-block;
}

.remove-contact-btn {
  white-space: nowrap;
}

.add-contact-btn-wrapper {
  margin-top: 16px;
  text-align: center;
}

.add-contact-btn {
  width: 100%;
  max-width: 300px;
}

.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

.save-button {
  height: 40px;
  padding: 0 24px;
  font-size: 14px;
  font-weight: 500;
  border-radius: 6px;
  background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
  border: none;
  transition: all 0.3s ease;
}

.save-button:hover:not(:disabled) {
  background: linear-gradient(135deg, #40a9ff 0%, #69c0ff 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.3);
}

.save-button:active:not(:disabled) {
  transform: translateY(0);
}

.cancel-button {
  height: 40px;
  padding: 0 24px;
  font-size: 14px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.cancel-button:hover {
  color: #1890ff;
  border-color: #1890ff;
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 富文本编辑器样式 */
.editor-wrapper {
  border-radius: 8px;
  overflow: hidden;
}

.editor-toolbar {
  background-color: #f5f5f5;
  padding: 12px 16px;
  border-bottom: 1px solid #e8e8e8;
}

.toolbar-info {
  display: flex;
  align-items: center;
  color: #666;
  font-size: 14px;
}

.toolbar-info .anticon {
  margin-right: 8px;
}

.markdown-editor-container {
  width: 100%;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.markdown-editor-container:hover {
  border-color: #1890ff;
}

.enhanced-editor {
  border-radius: 6px;
}

/* 富文本编辑器内部样式调整 */
.markdown-editor-container :deep(.v-md-editor) {
  border: none;
  border-radius: 0;
}

.markdown-editor-container :deep(.v-md-editor-preview),
.markdown-editor-container :deep(.v-md-editor__preview-wrapper) {
  background-color: #f9f9f9;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .personal-info-container {
    padding: 16px;
  }

  .personal-info-form {
    padding: 16px;
  }

  .personal-info-header h2 {
    font-size: 20px;
  }

  .avatar-large {
    width: 100px !important;
    height: 100px !important;
  }

  .form-fields-container {
    max-width: 100%;
  }

  .contact-method-controls {
    flex-direction: column;
    align-items: stretch;
  }

  .contact-type-select,
  .contact-value-input,
  .remove-contact-btn {
    width: 100%;
  }

  .remove-contact-btn {
    text-align: center;
  }

  .form-actions {
    flex-direction: column;
    gap: 12px;
  }

  .save-button,
  .cancel-button {
    width: 100%;
  }

  .cancel-button {
    margin-left: 0 !important;
  }
}
</style>